package com.atguigu.bigdata.chapter08;

import com.atguigu.bigdata.bean.HotItem;
import com.atguigu.bigdata.bean.UserBehavior;
import com.atguigu.bigdata.util.AtguiguUtil;
import org.apache.flink.api.common.RuntimeExecutionMode;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.KeyedProcessFunction;
import org.apache.flink.streaming.api.functions.windowing.ProcessWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;

import java.time.Duration;
import java.util.List;

/**
 * @Author lzc
 * @Date 2022/9/8 9:02
 */
public class Flink03_High_Project_TopN {
    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 2000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(1);
        env.setRuntimeMode(RuntimeExecutionMode.BATCH);
    
        env
            .readTextFile("input/UserBehavior.csv")
            .map(new MapFunction<String, UserBehavior>() {
                @Override
                public UserBehavior map(String line) throws Exception {
                    String[] data = line.split(",");
                    return new UserBehavior(
                        Long.valueOf(data[0]),
                        Long.valueOf(data[1]),
                        Integer.valueOf(data[2]),
                        data[3],
                        Long.parseLong(data[4]) * 1000  // 把s变成ms
                    );
                }
            })
            .assignTimestampsAndWatermarks(
                WatermarkStrategy
                    .<UserBehavior>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                    .withTimestampAssigner((ub, ts) -> ub.getTimestamp())
            )
            .filter(ub -> "pv".equals(ub.getBehavior()))
            // 统计每个商品在每个窗口内的点击量
            .keyBy(UserBehavior::getItemId)
            .window(TumblingEventTimeWindows.of(Time.hours(1)))
            .aggregate(
                new AggregateFunction<UserBehavior, Long, Long>() {
                    @Override
                    public Long createAccumulator() {
                        return 0L;
                    }
                
                    @Override
                    public Long add(UserBehavior value, Long accumulator) {
                        return accumulator + 1;
                    }
                
                    @Override
                    public Long getResult(Long accumulator) {
                        return accumulator;
                    }
                
                    @Override
                    public Long merge(Long a, Long b) {
                        return a + b;
                    }
                },
                new ProcessWindowFunction<Long, HotItem, Long, TimeWindow>() {
                    @Override
                    public void process(Long itemId,
                                        Context ctx,
                                        Iterable<Long> elements,
                                        Collector<HotItem> out) throws Exception {
                        Long clickCount = elements.iterator().next();
                    
                        out.collect(new HotItem(itemId, ctx.window().getEnd(), clickCount));
                    }
                }
            )
            // 后面要按照窗口结束时间keyBy, 按照点击排序, 需要传递下去的: 商品id, 窗口的结束时间, 点击量
            .keyBy(HotItem::getWEnd)
            .process(new KeyedProcessFunction<Long, HotItem, String>() {
    
                private ListState<HotItem> hotItemState;
                private ValueState<Boolean> isFirstState;
    
                @Override
                public void onTimer(long timestamp,
                                    OnTimerContext ctx,
                                    Collector<String> out) throws Exception {
                    // 排序取top3
                    List<HotItem> hotItemList = AtguiguUtil.toList(hotItemState.get());
                    hotItemList.sort((o1, o2) -> o2.getClickCount().compareTo(o1.getClickCount()));
                    
                    String msg = "\n-----------\n";
                    for (int i = 0, len = Math.min(3, hotItemList.size()); i < len; i++) {
                        msg += hotItemList.get(i) + "\n";
                    }
    
                    out.collect(msg);
    
                }
    
                @Override
                public void open(Configuration parameters) throws Exception {
                    isFirstState = getRuntimeContext().getState(
                        new ValueStateDescriptor<Boolean>("isFirstState", Boolean.class));
    
                    hotItemState = getRuntimeContext().getListState(
                        new ListStateDescriptor<HotItem>("hotItemState", HotItem.class)
                    );
                }
    
                @Override
                public void processElement(HotItem hotItem,
                                           Context ctx,
                                           Collector<String> out) throws Exception {
                    // 当第一条数据进来的时候(如何判断是否为第一条?), 注册一个 定时器: wEnd+2s,
                    if (isFirstState.value() == null) { // ?
                        // 表示第一条数据过来
                        // 注册定时器
                        ctx.timerService().registerEventTimeTimer(hotItem.getWEnd() + 2000);
                        // 更新状态
                        isFirstState.update(true);
                    }
                    // 来的每条数据需要先存储到List状态中
                    // 当定时  器触发的时候,就可以排序,取top3
                    hotItemState.add(hotItem);
                
                }
            })
            .print();
        
        env.execute();
    }
}
